package com.zx.sdk.league.member.baidu;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.baidu.mobads.sdk.api.AdView;
import com.baidu.mobads.sdk.api.AdViewListener;
import com.baidu.mobads.sdk.api.BDAdConfig;
import com.baidu.mobads.sdk.api.BDDialogParams;
import com.baidu.mobads.sdk.api.BaiduNativeManager;
import com.baidu.mobads.sdk.api.ExpressInterstitialAd;
import com.baidu.mobads.sdk.api.ExpressInterstitialListener;
import com.baidu.mobads.sdk.api.ExpressResponse;
import com.baidu.mobads.sdk.api.MobadsPermissionSettings;
import com.baidu.mobads.sdk.api.RequestParameters;
import com.baidu.mobads.sdk.api.RewardVideoAd;
import com.baidu.mobads.sdk.api.SplashAd;
import com.baidu.mobads.sdk.api.SplashInteractionListener;
import com.google.gson.Gson;
import com.zx.sdk.ZxSDK;
import com.zx.sdk.league.member.BaseLeagueMember;
import com.zx.sdk.listener.BaseZxBannerListener;
import com.zx.sdk.listener.BaseZxRewardListener;
import com.zx.sdk.listener.BaseZxShortVideoListener;
import com.zx.sdk.listener.BaseZxSplashListener;
import com.zx.sdk.model.AdInfo;
import com.zx.sdk.model.ReadyAdPosition;
import com.zx.sdk.model.Winner;
import com.zx.sdk.model.ZxError;
import com.zx.sdk.util.LogHelper;
import com.zx.sdk.util.UiHelper;
import com.zx.sdk.view.widget.BaseNewsAdView;

import org.json.JSONObject;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class BaiDu extends BaseLeagueMember<Object, Object, Object, ExpressInterstitialAd, Object> {

    private Winner splashWinner = Winner.load("splashWinner");
    private Winner rewardWinner = Winner.load("rewardWinner");

    @Override
    public String getName() {
        return "bd";
    }

    @Override
    protected void onInit(Context context, String appId, boolean initialized) {
        new BDAdConfig.Builder()
                .setAppName(ZxSDK.getAppName())
                // 2、应用在mssp平台申请到的appsid，和包名一一对应，此处设置等同于在AndroidManifest.xml里面设置
                .setAppsid(appId)
                .setHttps(false)
                // 3、设置下载弹窗的类型和按钮动效样式，可选
                .setDialogParams(new BDDialogParams.Builder()
                        .setDlDialogType(BDDialogParams.TYPE_BOTTOM_POPUP)
                        .setDlDialogAnimStyle(BDDialogParams.ANIM_STYLE_NONE)
                        .build())
                .build(ZxSDK.getContext())
                .init();
        // 设置SDK可以使用的权限，包含：设备信息、定位、存储、APP LIST
        // 注意：建议授权SDK读取设备信息，SDK会在应用获得系统权限后自行获取IMEI等设备信息
        // 授权SDK获取设备信息会有助于提升ECPM
        MobadsPermissionSettings.setPermissionReadDeviceID(true);
        MobadsPermissionSettings.setPermissionLocation(true);
        MobadsPermissionSettings.setPermissionStorage(true);
        MobadsPermissionSettings.setPermissionAppList(true);
    }

    @Override
    protected void onLoadSplash(AdInfo adInfo, ViewGroup container, String mode, String type, BaseZxSplashListener listener) {
        if (AdInfo.AD_TYPE_EXPRESS_INTERSTITIAL_AD == adInfo.getAdType()) {
            onLoadInterstitial((Activity) container.getContext(), adInfo, mode, type, new BaseZxRewardListener() {
                @Override
                public void onADClick() {
                    listener.onADClicked();
                }

                @Override
                public void onADClose() {
                    listener.onADDismissed();
                }

                @Override
                public void onADExpose() {
                    listener.onADExposure();
                }

                @Override
                public void onADLoad() {
                    listener.onADLoaded(0L);
                }

                @Override
                public void onReward(@NonNull Map<String, Object> map) {

                }

                @Override
                public void onVideoCached() {

                }

                @Override
                public void onVideoComplete() {

                }

                @Override
                public void onPreLoadADError(ZxError error) {
                    listener.onPreLoadNoAD(error);
                }

                @Override
                public void onRewardStepVerify(int taskType, int currentTaskStatus) {

                }

                @Override
                public void onAdSkip(float v) {

                }

                @Override
                public void onVideoPlayError(ZxError error) {
                }

                @Override
                public void onNoAD(ZxError error) {
                    listener.onNoAD(error);
                }

                @Override
                public void onPreloading() {
                    listener.onPreloading();
                }

                @Override
                public void onLoaded() {
                    listener.onLoaded();
                }
            });
            return;
        }
        SplashAd[] splashAdContainer = new SplashAd[1];
        RequestParameters.Builder paramsBuilder = new RequestParameters.Builder()
                .addExtra(SplashAd.KEY_TIMEOUT, "4200")// sdk内部默认超时时间为4200，单位：毫秒
                .addExtra(SplashAd.KEY_DISPLAY_DOWNLOADINFO, "true")// sdk内部默认值为true
                .addExtra(SplashAd.KEY_POPDIALOG_DOWNLOAD, "true");// 用户点击开屏下载类广告时，是否弹出Dialog// 此选项设置为true的情况下，会覆盖掉 {SplashAd.KEY_DISPLAY_DOWNLOADINFO} 的设置
        if (splashWinner != null && adInfo.isBiddingPosition()) {
            paramsBuilder.addCustExt("A", splashWinner.getDsp()).addCustExt("B", splashWinner.getCpm());
        }
        splashAdContainer[0] = new SplashAd(container.getContext(), adInfo.getMapPid(),
                // 如果开屏需要load广告和show广告分开，请参考类RSplashManagerActivity的写法
                // 如果需要修改开屏超时时间、隐藏工信部下载整改展示，请设置下面代码;
                paramsBuilder.build()
                , new SplashInteractionListener() {
            @Override
            public void onLpClosed() {
                listener.onADDismissed(BaiDu.this, adInfo);
            }

            @Override
            public void onAdDismissed() {
                listener.onADDismissed(BaiDu.this, adInfo);
            }

            @Override
            public void onADLoaded() {
                listener.onADLoaded(BaiDu.this, -1, adInfo);
                if (ZxSDK.FETCH_ONLY.equals(mode)) {
                    saveSplash(adInfo.getMapPid(), splashAdContainer[0], container);
                }
            }

            @Override
            public void onAdFailed(String msg) {
                switch (mode) {
                    case ZxSDK.FETCH_ONLY:
                        listener.onPreLoadNoAD(BaiDu.this, new ZxError("-1", msg), adInfo);
                        break;
                    case ZxSDK.FETCH_AND_SHOW:
                        listener.onNoAD(BaiDu.this, new ZxError("-1", msg), adInfo);
                        break;
                }
                splashAdContainer[0].biddingFail("100");
            }

            @Override
            public void onAdPresent() {
                listener.onADExposure(BaiDu.this, adInfo);
            }

            @Override
            public void onAdClick() {
                listener.onADClicked(BaiDu.this, adInfo);
            }

            @Override
            public void onAdCacheSuccess() {
            }

            @Override
            public void onAdCacheFailed() {
            }
        });
        switch (mode) {
            case ZxSDK.FETCH_ONLY:
                splashAdContainer[0].load();
                break;
            case ZxSDK.FETCH_AND_SHOW:
                splashAdContainer[0].loadAndShow(container);
                break;
        }
    }

    @Override
    public boolean onShowSplash(AdInfo adInfo, ViewGroup container, @Nullable Object splash, BaseZxSplashListener listener) {
        if (splash instanceof SplashAd && ((SplashAd) splash).isReady()) {
            ((SplashAd) splash).show(container);
            return true;
        } else if (splash instanceof ExpressInterstitialAd) {
            ((ExpressInterstitialAd) splash).show((Activity) container.getContext());
            return true;
        }
        return false;
    }

    @Override
    public void onLoadReward(Activity context, AdInfo adInfo, String mode, String type, BaseZxRewardListener listener) {
        if (AdInfo.AD_TYPE_EXPRESS_INTERSTITIAL_AD == adInfo.getAdType()) {
            onLoadInterstitial(context, adInfo, mode, type, listener);
            return;
        }
        RewardVideoAd[] rewardVideoAdContainer = new RewardVideoAd[1];
        rewardVideoAdContainer[0] = new RewardVideoAd(context, adInfo.getMapPid(), new RewardVideoAd.RewardVideoAdListener() {
            @Override
            public void onAdShow() {
                listener.onADExpose(BaiDu.this, adInfo);
            }

            @Override
            public void onAdClick() {
                listener.onADClick(BaiDu.this, adInfo);
            }

            @Override
            public void onAdClose(float v) {
                listener.onADClose(BaiDu.this, adInfo);
            }

            @Override
            public void onAdFailed(String s) {
                switch (mode) {
                    case ZxSDK.FETCH_ONLY:
                        listener.onPreLoadADError(BaiDu.this, new ZxError("-1", s), adInfo);
                        break;
                    case ZxSDK.FETCH_AND_SHOW:
                        listener.onNoAD(BaiDu.this, new ZxError("-1", s), adInfo);
                        break;
                }
                rewardVideoAdContainer[0].biddingFail("100");
            }

            @Override
            public void onVideoDownloadSuccess() {

            }

            @Override
            public void onVideoDownloadFailed() {

            }

            @Override
            public void playCompletion() {
                listener.onVideoComplete(BaiDu.this, adInfo);
            }

            @Override
            public void onAdLoaded() {
                if (rewardVideoAdContainer[0].isReady()) {
                    listener.onADLoad(BaiDu.this, adInfo);
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY:
                            saveReward(adInfo.getMapPid(), rewardVideoAdContainer[0]);
                            break;
                        case ZxSDK.FETCH_AND_SHOW:
                            rewardVideoAdContainer[0].show();
                            break;
                    }
                } else {
                    listener.onNoAD(BaiDu.this, new ZxError("-1", "isNotReady"), adInfo);
                    rewardVideoAdContainer[0].biddingFail("100");
                }
            }

            @Override
            public void onAdSkip(float playScale) {
                listener.onAdSkip(BaiDu.this, playScale, adInfo);
            }

            @Override
            public void onRewardVerify(boolean b) {
                if (b) {
                    listener.onReward(BaiDu.this, Collections.emptyMap(), adInfo);
                }
            }
        }, false);
        rewardVideoAdContainer[0].setDownloadAppConfirmPolicy(RewardVideoAd.DOWNLOAD_APP_CONFIRM_NEVER);
        if (rewardWinner != null && adInfo.isBiddingPosition()) {
            rewardVideoAdContainer[0].setRequestParameters(new RequestParameters.Builder()
                    .addCustExt("A", rewardWinner.getDsp())
                    .addCustExt("B", rewardWinner.getCpm())
                    .build()
            );
        }
        rewardVideoAdContainer[0].setUserId(ZxSDK.getUid());
        rewardVideoAdContainer[0].setExtraInfo(new Gson().toJson(adInfo));
        rewardVideoAdContainer[0].setShowDialogOnSkip(false);
        rewardVideoAdContainer[0].load();
    }

    @Override
    public boolean onShowReward(Activity context, AdInfo adInfo, @Nullable Object reward, BaseZxRewardListener listener) {
        if (reward instanceof RewardVideoAd) {
            ((RewardVideoAd) reward).show();
            return true;
        } else if (reward instanceof ExpressInterstitialAd) {
            onShowInterstitial(context, adInfo, (ExpressInterstitialAd) reward, listener);
            return true;
        }
        return false;
    }

    @Override
    public void onLoadInterstitial(Activity context, AdInfo adInfo, String mode, String type, BaseZxRewardListener listener) {
        final RequestParameters requestParameters = new RequestParameters.Builder().build();
        // 在请求前取输入框中的广告位id
        ExpressInterstitialAd expressInterstitialAd = new ExpressInterstitialAd(context, adInfo.getMapPid());
        expressInterstitialAd.setLoadListener(new ExpressInterstitialListener() {
            @Override
            public void onADLoaded() {

            }

            @Override
            public void onAdClick() {
                listener.onADClick(BaiDu.this, adInfo);
            }

            @Override
            public void onAdClose() {
                if (ZxSDK.REWARD.equals(adInfo.getDisplay())) {
                    listener.onReward(BaiDu.this, Collections.emptyMap(), adInfo);
                }
                listener.onADClose(BaiDu.this, adInfo);
            }

            @Override
            public void onAdFailed(int i, String s) {
                switch (mode) {
                    case ZxSDK.FETCH_ONLY:
                        listener.onPreLoadADError(BaiDu.this, new ZxError(i + "", s), adInfo);
                        break;
                    case ZxSDK.FETCH_AND_SHOW:
                        listener.onNoAD(BaiDu.this, new ZxError(i + "", s), adInfo);
                        break;
                }
                expressInterstitialAd.biddingFail("100");
            }

            @Override
            public void onNoAd(int i, String s) {
                switch (mode) {
                    case ZxSDK.FETCH_ONLY:
                        listener.onPreLoadADError(BaiDu.this, new ZxError(i + "", s), adInfo);
                        break;
                    case ZxSDK.FETCH_AND_SHOW:
                        listener.onNoAD(BaiDu.this, new ZxError(i + "", s), adInfo);
                        break;
                }
                expressInterstitialAd.biddingFail("100");
            }

            @Override
            public void onADExposed() {
                listener.onADExpose(BaiDu.this, adInfo);
            }

            @Override
            public void onADExposureFailed() {

            }

            @Override
            public void onAdCacheSuccess() {
                if (expressInterstitialAd.isReady()) {
                    listener.onADLoad(BaiDu.this, adInfo);
                    switch (mode) {
                        case ZxSDK.FETCH_ONLY:
                            if (ZxSDK.SPLASH.equals(adInfo.getDisplay())) {
                                saveSplash(adInfo.getMapPid(), expressInterstitialAd, null);
                            } else if (ZxSDK.REWARD.equals(adInfo.getDisplay())) {
                                saveReward(adInfo.getMapPid(), expressInterstitialAd);
                            } else if (ZxSDK.INTERSTITIAL.equals(adInfo.getDisplay())) {
                                saveInterstitial(adInfo.getMapPid(), expressInterstitialAd);
                            }
                            break;
                        case ZxSDK.FETCH_AND_SHOW:
                            expressInterstitialAd.show();
                            break;
                    }
                } else {
                    listener.onNoAD(BaiDu.this, new ZxError("-1", "isNotReady"), adInfo);
                    expressInterstitialAd.biddingFail("100");
                }
            }

            @Override
            public void onAdCacheFailed() {
                switch (mode) {
                    case ZxSDK.FETCH_ONLY:
                        listener.onPreLoadADError(BaiDu.this, new ZxError("-1", "onAdCacheFailed"), adInfo);
                        break;
                    case ZxSDK.FETCH_AND_SHOW:
                        listener.onNoAD(BaiDu.this, new ZxError("-1", "onAdCacheFailed"), adInfo);
                        break;
                }
                expressInterstitialAd.biddingFail("100");
            }

            @Override
            public void onLpClosed() {

            }

            @Override
            public void onVideoDownloadSuccess() {

            }

            @Override
            public void onVideoDownloadFailed() {

            }
        });
        expressInterstitialAd.setDownloadListener(new ExpressInterstitialAd.InterAdDownloadWindowListener() {
            @Override
            public void adDownloadWindowShow() {

            }

            @Override
            public void adDownloadWindowClose() {

            }

            @Override
            public void onADPrivacyClick() {

            }

            @Override
            public void onADPrivacyClose() {

            }

            @Override
            public void onADPermissionShow() {

            }

            @Override
            public void onADPermissionClose() {

            }
        });
        // 设置下载弹窗，默认为false
        expressInterstitialAd.setDialogFrame(false);
        // 【可选】【Bidding】设置广告的底价，单位：分
//        expressInterstitialAd.setBidFloor(100);
        // 【非必要】设置传参
        expressInterstitialAd.setRequestParameters(requestParameters);
        // 请求广告
        expressInterstitialAd.load();
    }

    @Override
    public boolean onShowInterstitial(Activity context, AdInfo adInfo, @Nullable ExpressInterstitialAd interstitial, BaseZxRewardListener listener) {
        try {
            interstitial.show(context);
            return true;
        } catch (Throwable e) {
            return false;
        }
    }

    /**
     * 获取 cpm | 单位=分
     *
     * @return -1=为加载到资源
     */
    @Override
    public int getCpmByPid(String type, String pid) {
        int cpm = super.getCpmByPid(type, pid);
        try {
            switch (type) {
                case ZxSDK.SPLASH:
                    if (splashMap.containsKey(pid)) {
                        Object adv = splashMap.get(pid);
                        if (adv instanceof SplashAd) {
                            cpm = Integer.parseInt(((SplashAd) adv).getECPMLevel());
                        } else if (adv instanceof ExpressInterstitialAd) {
                            cpm = Integer.parseInt(((ExpressInterstitialAd) adv).getECPMLevel());
                        }
                    }
                case ZxSDK.REWARD:
                    if (rewardMap.containsKey(pid)) {
                        Object rewardAd = rewardMap.get(pid);
                        if (rewardAd instanceof RewardVideoAd) {
                            cpm = Integer.parseInt(((RewardVideoAd) rewardAd).getECPMLevel());
                        } else if (rewardAd instanceof ExpressInterstitialAd) {
                            cpm = Integer.parseInt(((ExpressInterstitialAd) rewardAd).getECPMLevel());
                        }
                    }
                case ZxSDK.INTERSTITIAL:
                    if (interstitialMap.containsKey(pid)) {
                        cpm = Integer.parseInt(interstitialMap.get(pid).getECPMLevel());
                    }
                case ZxSDK.BANNER:
                    if (bannerMap.containsKey(pid)) {
                        Object o = bannerMap.get(pid);
                        if (o instanceof ExpressResponse) {
                            cpm = Integer.parseInt(((ExpressResponse) o).getECPMLevel());
                        }
                    }
            }
        } catch (Exception exception) {
            LogHelper.d("Bd getCpmByPid exception " + exception.getMessage());
        }
        cpmCache.put(type + pid, cpm);
        return cpm;
    }

    @Override
    public void notifyBiddingWin(String type, String mapPid, @Nullable ReadyAdPosition loser) {
        // 百度广告竞价成功时，调用此接口回传排序第二的价格（价格单位：分）
        String secondPrice = "0";
        if (loser != null) {
            secondPrice = String.valueOf(loser.getCpm());
        }
        if (ZxSDK.REWARD.equals(type)) {
            Object rewardVideoAD = rewardMap.get(mapPid);
            if (rewardVideoAD == null) {
                return;
            }
            // 百度广告竞价成功时，调用此接口回传排序第二的价格（价格单位：分）
            rewardWinner = new Winner("rewardWinner", "bd", getCpmByPid(type, mapPid));
            if (rewardVideoAD instanceof RewardVideoAd) {
                ((RewardVideoAd) rewardVideoAD).biddingSuccess(secondPrice);
            } else if (rewardVideoAD instanceof ExpressInterstitialAd) {
                ((ExpressInterstitialAd) rewardVideoAD).biddingSuccess(secondPrice);
            }
        } else if (ZxSDK.SPLASH.equals(type)) {
            Object adv = splashMap.get(mapPid);
            splashWinner = new Winner("splashWinner", "bd", getCpmByPid(type, mapPid));
            if (adv instanceof SplashAd) {
                ((SplashAd) adv).biddingSuccess(secondPrice);
            } else if (adv instanceof ExpressInterstitialAd) {
                ((ExpressInterstitialAd) adv).biddingSuccess(secondPrice);
            }
        } else if (ZxSDK.INTERSTITIAL.equals(type)) {
            ExpressInterstitialAd ad = interstitialMap.get(mapPid);
            if (ad == null) {
                return;
            }
            ad.biddingSuccess(secondPrice);
        } else if (ZxSDK.BANNER.equals(type)) {
            Object o = bannerMap.get(mapPid);
            if (o instanceof ExpressResponse ad) {
                ad.biddingSuccess(secondPrice);
            }
        }
        LogHelper.d(getName(), "notifyBiddingWin", mapPid, "selfPrice =" + getCpmByPid(type, mapPid), "LoserPrice = " + secondPrice);
    }

    @Override
    public void notifyBiddingLose(String type, String mapPid, ReadyAdPosition winner, ZxSDK.LoseReason reason) {
        LinkedHashMap<String, Object> winInfo = new LinkedHashMap<>();
        if (winner != null) {
            winInfo.put("ecpm", winner.getCpm());
            winInfo.put("adn", getAdn(winner.getLeague()));
        }
        if (ZxSDK.REWARD.equals(type)) {
            Object rewardVideoAD = rewardMap.get(mapPid);
            if (rewardVideoAD == null) {
                return;
            }
            rewardWinner = new Winner("rewardWinner", winner.getLeague(), winner.getCpm());
            if (rewardVideoAD instanceof RewardVideoAd) {
                ((RewardVideoAd) rewardVideoAD).biddingFail(getLoseReason(reason), winInfo);
            } else if (rewardVideoAD instanceof ExpressInterstitialAd) {
                ((ExpressInterstitialAd) rewardVideoAD).biddingFail(getLoseReason(reason), winInfo);
            }
        } else if (ZxSDK.SPLASH.equals(type)) {
            Object adv = splashMap.get(mapPid);
            splashWinner = new Winner("splashWinner", winner.getLeague(), winner.getCpm());
            if (adv instanceof SplashAd) {
                ((SplashAd) adv).biddingFail(getLoseReason(reason), winInfo);
            } else if (adv instanceof ExpressInterstitialAd) {
                ((ExpressInterstitialAd) adv).biddingFail(getLoseReason(reason), winInfo);
            }
        } else if (ZxSDK.INTERSTITIAL.equals(type)) {
            ExpressInterstitialAd ad = interstitialMap.get(mapPid);
            if (ad == null) {
                return;
            }
            ad.biddingFail(getLoseReason(reason), winInfo);
        } else if (ZxSDK.BANNER.equals(type)) {
            Object o = bannerMap.get(mapPid);
            if (o instanceof ExpressResponse ad) {
                ad.biddingFail(getLoseReason(reason), winInfo);
            }
        }
        LogHelper.d(getName(), "notifyBiddingLose", mapPid, "selfPrice =" + getCpmByPid(type, mapPid), "WinnerPrice = " + winner.getCpm(), "winInfo = " + winInfo);
    }

    private Integer getAdn(String league) {
        return switch (league) {
            case "ks" -> 3;
            case "sig" -> 4;
            default -> 10;
        };
    }

    protected String getLoseReason(ZxSDK.LoseReason reason) {
        switch (reason) {
            case NO_AD:
                return "100";
            case LOW_PRICE:
            default:
                return "203";
        }
    }

    @Override
    public void onLoadBanner(Activity context, ViewGroup container, AdInfo adInfo, String mode, String type, BaseZxBannerListener listener) {
        if ("2001".equals(ZxSDK.getAppId())) {
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(UiHelper.getScreenWidth(), Math.round(UiHelper.getScreenWidth() * (3 / 20F)));
            AdView adView = new AdView(context, adInfo.getMapPid());
            adView.setListener(new AdViewListener() {
                @Override
                public void onAdReady(AdView adView) {
                    listener.onAdReady(adView, BaiDu.this, adInfo);
                }

                @Override
                public void onAdShow(JSONObject jsonObject) {
                    listener.onAdShow(jsonObject, BaiDu.this, adInfo);
                    addCloseBtnToBanner(container, () -> dismissBanner(container));
                }

                @Override
                public void onAdClick(JSONObject jsonObject) {
                    listener.onAdClick(jsonObject, BaiDu.this, adInfo);
                }

                @Override
                public void onAdFailed(String s) {
                    listener.onAdFailed(new ZxError("-1", s), BaiDu.this, adInfo);
                }

                @Override
                public void onAdSwitch() {
                    listener.onAdSwitch(BaiDu.this, adInfo);
                }

                @Override
                public void onAdClose(JSONObject jsonObject) {
                    listener.onAdClose(jsonObject, BaiDu.this, adInfo);
                    dismissBanner(container);
                }
            });
            adView.setLayoutParams(layoutParams);
            switch (mode) {
                case ZxSDK.FETCH_ONLY:
                    saveBanner(adInfo.getMapPid(), adView);
                    break;
                case ZxSDK.FETCH_AND_SHOW:
                    onShowBanner(context, adInfo, container, adView, listener);
                    break;
            }
        } else {
            BaiduNativeManager mBaiduNativeManager = new BaiduNativeManager(context.getApplicationContext(), adInfo.getMapPid());
            final RequestParameters requestParameters = new RequestParameters.Builder().downloadAppConfirmPolicy(RequestParameters.DOWNLOAD_APP_CONFIRM_ONLY_MOBILE).build();
            final BaiduNativeManager.ExpressAdListener expressAdListener = new BaiduNativeManager.ExpressAdListener() {
                @Override
                public void onNativeLoad(List<ExpressResponse> nativeResponses) {
                    if (nativeResponses == null || nativeResponses.isEmpty()) {
                        return;
                    }
                    ExpressResponse expressResponse = nativeResponses.get(0);
                    expressResponse.setInteractionListener(new ExpressResponse.ExpressInteractionListener() {
                        @Override
                        public void onAdClick() {
                            listener.onAdClick(new Object(), BaiDu.this, adInfo);
                        }

                        @Override
                        public void onAdExposed() {
                            listener.onAdShow(new Object(), BaiDu.this, adInfo);
                        }

                        @Override
                        public void onAdRenderFail(View adView, String reason, int code) {
                            listener.onAdFailed(new ZxError(String.valueOf(code), reason), BaiDu.this, adInfo);
                        }

                        @Override
                        public void onAdRenderSuccess(View adView, float width, float height) {
                            switch (mode) {
                                case ZxSDK.FETCH_ONLY:
                                    saveBanner(adInfo.getMapPid(), expressResponse);
                                    break;
                                case ZxSDK.FETCH_AND_SHOW:
                                    onShowBanner(context, adInfo, container, expressResponse, listener);
                                    break;
                            }
                        }

                        @Override
                        public void onAdUnionClick() {

                        }
                    });
                    expressResponse.setAdDislikeListener(new ExpressResponse.ExpressDislikeListener() {
                        @Override
                        public void onDislikeWindowShow() {

                        }

                        @Override
                        public void onDislikeItemClick(String reason) {
                            container.removeAllViews();
                        }

                        @Override
                        public void onDislikeWindowClose() {

                        }
                    });
                    expressResponse.setAdCloseListener(it -> {
                        if (container != null) {
                            container.removeView(it.getExpressAdView());
                        }
                    });
                    expressResponse.render();
                }

                @Override
                public void onNoAd(int code, String msg) {
                    listener.onAdFailed(new ZxError(String.valueOf(code), msg), BaiDu.this, adInfo);
                }

                @Override
                public void onNativeFail(int errorCode, String message) {
                    listener.onAdFailed(new ZxError(String.valueOf(errorCode), message), BaiDu.this, adInfo);
                }

                @Override
                public void onVideoDownloadSuccess() {

                }

                @Override
                public void onVideoDownloadFailed() {
                    listener.onAdFailed(new ZxError("-1", "onVideoDownloadFailed"), BaiDu.this, adInfo);
                }

                @Override
                public void onLpClosed() {
                    listener.onAdClose(new Object(), BaiDu.this, adInfo);
                }
            };
            mBaiduNativeManager.loadExpressAd(requestParameters, expressAdListener);
        }
    }

    @Override
    public boolean onShowBanner(Activity activity, AdInfo adInfo, ViewGroup container, Object adView, BaseZxBannerListener listener) {
        container.removeAllViews();
        if (adView instanceof ExpressResponse) {
            container.addView(((ExpressResponse) adView).getExpressAdView());
            addCloseBtnToBanner(container, () -> dismissBanner(container));
        } else if (adView instanceof AdView) {
            container.addView((AdView) adView);
        }
        return true;
    }

    private void dismissBanner(ViewGroup container) {
        container.removeAllViews();
    }
    @Override
    protected void onDestroyBanner(Object banner) {

    }

    @Override
    protected Fragment onGetShortVideoFragment(BaseZxShortVideoListener listener, AdInfo adInfo) {
        BaiduFragment baiduFragment = new BaiduFragment();
        Bundle bundle = new Bundle();
        bundle.putString("appId", adInfo.getMapAppid());
        baiduFragment.setArguments(bundle);
        return baiduFragment;
    }

    @Override
    protected BaseNewsAdView onGetNewsView(Context context, AdInfo adInfo) {
        return new BaiduNewsAdView(context, adInfo);
    }
}
